<template>
  <div class="communicate">
    <van-nav-bar
      left-arrow
      class="title-bar"
      title="常用联系人"
      :border="false"
      @click-left="$router.push('/my')"
    />
    <!-- 搜索 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        center
        placeholder="请输入您想搜索的内容"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <!-- 搜索建议 -->
    <search-suggestion
      @search="onSearch"
      v-if="searchText"
      :search-text="searchText"
    />
    <!-- 搜索历史 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    />
  </div>
</template>

<script>
import searchHistory from './components/search-history'
import searchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storage'
export default {
  data() {
    return {
      searchText: '',
      isResultShow: false, // 控制搜索结果的显示状态
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORY') || [] // 历史
    }
  },
  components: {
    searchHistory,
    searchSuggestion
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      this.searchText = val

      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      console.log(this.searchHistories)
      this.isResultShow = true
    },
    onCancel() {
      this.$router.go(-1)
    }
  },
  watch: {
    searchHistories(value) {
      // 同步搜索数据到本地
      setItem('TOUTIAO_SEARCH_HISTORY', value)
    }
  }
}
</script>

<style scoped lang="less">
.communicate {
  .title-bar {
    height: 128px;
    width: 100%;
    padding-top: 40px;
    box-sizing: border-box;
    /deep/.van-nav-bar__title {
      font-size: 34px;
      font-weight: bold;
    }
    /deep/.van-icon {
      font-size: 48px;
      color: #000;
    }
  }
  .van-search__content {
    height: 80px;
  }
  .van-search__action {
    color: #3290f3;
  }
}
</style>
